package com.sbs.gaoxinqutoilet.utils;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sbs.gaoxinqutoilet.entity.BaseEntity;
import com.sbs.gaoxinqutoilet.http.Request;
import com.sbs.gaoxinqutoilet.utils.loading.LoadingDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.http.okhttp.request.RequestCall;

import org.json.JSONObject;

import java.io.File;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

public class HttpUtils {

    protected static JSONObject JsonObject = null;


    //handler发消息的几个常量

    public static final int version_msg = 1;
    public static final int download_msg = 2;


    public static void requestGet(Context context, String url, final Request request) {
        if (NetworkUtils.isConnected(context)) {

            OkHttpUtils.get().url(url).tag(context).build().execute(new StringCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    request.error("失败"+e.getMessage());
                }

                @Override
                public void onResponse(String response, int id) {
                    request.success(response);
                }
            });
        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
        }
    }
    public static void requestPostUrl(Context context, String url, final Request request) {
        if (NetworkUtils.isConnected(context)) {

            OkHttpUtils.post().url(url).tag(context).build().execute(new StringCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    request.error("失败"+e.getMessage());
                }

                @Override
                public void onResponse(String response, int id) {
                    request.success(response);
                }
            });
        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
        }
    }

    /**
     * GET请求
     *
     * @param context
     * @param url
     * @param map
     * @param request
     */
    public static void requestGet(Context context, String url,
                                  Map<String, String> map, final Request request) {

        if (NetworkUtils.isConnected(context)) {


            RequestCall call = OkHttpUtils.get().url(url).params(map).tag(context).build();


            call.execute(new StringCallback() {

                @Override
                public void onResponse(String response, int id) {
                    request.success(response);
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    request.error("失败"+e.getMessage());
                }

            });

        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
        }
    }

    /**
     * Post请求
     *
     * @param context
     * @param url
     * @param map
     * @param request
     */
    public static void requestPost(Context context, String url,
                                   Map<String, String> map, String imei, final Request request) {


        if (NetworkUtils.isConnected(context)) {
//            String encrypt = null;
//            try {
//               encrypt = DESUtils.encrypt(new Gson().toJson(map), imei);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }

            RequestCall call = OkHttpUtils.post().url(url).params(map).tag(context).build();
            if (call == null) {
                Toast.makeText(context, "call为空", Toast.LENGTH_LONG).show();
            }
            call.execute(new StringCallback() {

                @Override
                public void onResponse(String response, int id) {
                    request.success(response);
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    request.error(call.toString() + "失败" + e.toString());
                }
            });

        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
        }
    }



    /**
     * Post请求
     *
     * @param context
     * @param url
     * @param map
     * @param request
     */
    public static void requestPost(Context context, String url,
                                   Map<String, String> map, final Request request) {

        if (NetworkUtils.isConnected(context)) {
//            String encrypt = null;
//            try {
//               encrypt = DESUtils.encrypt(new Gson().toJson(map), imei);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }

            RequestCall call = OkHttpUtils.post().url(url).params(map).tag(context).build();
            if (call == null) {
                Toast.makeText(context, "call为空", Toast.LENGTH_LONG).show();
            }
            call.execute(new StringCallback() {

                @Override
                public void onResponse(String response, int id) {
                    request.success(response);
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    request.error(call.toString() + "失败" + e.toString());
                }
            });

        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
            LoadingDialog.cancelLoadingDialog();
        }
    }

    /**
     * 补加参数的post请求
     * @param context
     * @param url
     * @param request
     */
    public static void requestPost(Context context, String url, final Request request) {
        if (NetworkUtils.isConnected(context)) {

            RequestCall call = OkHttpUtils.post().url(url).tag(context).build();
            if (call == null) {
                Toast.makeText(context, "call为空", Toast.LENGTH_LONG).show();
            }
            call.execute(new StringCallback() {

                @Override
                public void onResponse(String response, int id) {
                    request.success(response);
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    request.error(call.toString() + "失败" + e.toString());
                }
            });

        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
        }
    }

    public static void requestPostGson(Context context, String url, BaseEntity addnewentity, final Request request){
        if (NetworkUtils.isConnected(context)) {

            String toJson = new Gson().toJson(addnewentity);
            Log.i("postGson", "requestPostGson: "+toJson);
            OkHttpUtils.postString().url(url)
                    //.addHeader("Content-type","application/x-www-form-urlencoded")
                    .content(new Gson().toJson(addnewentity)).tag(context)
                    .build().execute(new StringCallback() {
                @Override
                public void onResponse(String response, int id) {
                    request.success(response);
                    // DialogUtil.dismissProgressDialog();// 隐藏进度条Dialog
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    request.error("失败");
                    //DialogUtil.dismissProgressDialog();// 隐藏进度条Dialog
                }

            });

        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
            //DialogUtil.dismissProgressDialog();// 隐藏进度条Dialog
        }

    }
    public static void requestPostYanShouGson(Context context, String url, BaseEntity addnewentity,Map<String, String> map, final Request request){
        if (NetworkUtils.isConnected(context)) {

            String toJson = new Gson().toJson(addnewentity);
            //String toJson = new Gson().toJson(map);
            Log.i("postGson", "requestPostGson: "+toJson);
            OkHttpUtils.postString().url(url)
                    .addHeader("Content-type","application/x-www-form-urlencoded")
                    .mediaType(MediaType.parse("application/json"))
                    //.mediaType(MediaType.parse("multipart"))
                    .content(new Gson().toJson(addnewentity)).tag(context)
                    .build().execute(new StringCallback() {
                @Override
                public void onResponse(String response, int id) {
                    request.success(response);
                    // DialogUtil.dismissProgressDialog();// 隐藏进度条Dialog
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    request.error("失败");
                    //DialogUtil.dismissProgressDialog();// 隐藏进度条Dialog
                }

            });

        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
            //DialogUtil.dismissProgressDialog();// 隐藏进度条Dialog
        }

    }

    /**
     * 提交一个Gson字符串到服务器端。
     *
     * @param context
     * @param url
     * @param map
     * @param request
     */
    public static void requestPostGson(Context context, String url,
                                       Map<String, Object> map, final Request request) {
        // DialogUtil.showProgressDialog(context, "正在请求网络，请稍后...");// 弹出Dialog提示，优化用户体验。

        if (NetworkUtils.isConnected(context)) {

            String json=new Gson().toJson(map);
            OkHttpUtils.postString().url(url)
                    //.addHeader("Content-type","application/x-www-form-urlencoded")
                    .mediaType(MediaType.parse("application/json;charset=utf-8"))
                    .content(json)
                    .tag(context)
                    .build().execute(new StringCallback() {
                @Override
                public void onResponse(String response, int id) {
                    request.success(response);
                    // DialogUtil.dismissProgressDialog();// 隐藏进度条Dialog
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    request.error("失败");
                    //DialogUtil.dismissProgressDialog();// 隐藏进度条Dialog
                }

            });

        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
            //DialogUtil.dismissProgressDialog();// 隐藏进度条Dialog
        }
    }

    /**
     * 提交混合File到服务器端。
     *
     * @param context
     * @param url
     * @param file
     * @param request
     */
    public static void requestPostFileUpload(Context context, String url, String fileDataName, File file, String adjunctType, String fnum,
                                             final Request request) {

        if (NetworkUtils.isConnected(context)) {
            //
            OkHttpUtils.post().url(url).addFile("filedata", fileDataName, file).addParams("adjunct_type", adjunctType).addParams("fnum", fnum).tag(context).build()
                    .execute(new StringCallback() {

                        @Override
                        public void onResponse(String response, int id) {
                            request.success(response);
                            LogUtils.e("jsonStr", response);
                        }

                        @Override
                        public void onError(Call call, Exception e, int id) {
                            request.error(call.toString() + "失败" + e.toString());
                        }

                    });

        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
        }
    }
    public static void requestPostFileUploades(Context context, String url, String fileDataName, File file,
                                             final Request request) {

        if (NetworkUtils.isConnected(context)) {

            OkHttpUtils.post().url(url).addFile("uploadFile", fileDataName, file).tag(context).build()
                    .execute(new StringCallback() {

                        @Override
                        public void onResponse(String response, int id) {
                            request.success(response);
                            LogUtils.e("jsonStr", response);
                        }

                        @Override
                        public void onError(Call call, Exception e, int id) {
                            request.error(call.toString() + "失败" + e.toString());
                        }

                    });

        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
        }
    }

    public static void requestPostFileMapUploades(Context context, String url, String fileDataName, File file,
                                                  Map<String,String> params,final Request request) {

        if (NetworkUtils.isConnected(context)) {

            OkHttpUtils.post().url(url).addFile("uploadFile", fileDataName, file)
                    .params(params).tag(context).build()
                    .execute(new StringCallback() {

                        @Override
                        public void onResponse(String response, int id) {
                            request.success(response);
                            LogUtils.e("jsonStr", response);
                        }

                        @Override
                        public void onError(Call call, Exception e, int id) {
                            request.error(call.toString() + "失败" + e.toString());
                        }

                    });

        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
        }
    }
    public static void requestPostFileUploadesLocation(Context context, String url, String fileDataName, File file,
                                                       Map<String,String> params, final Request request) {

        if (NetworkUtils.isConnected(context)) {

            OkHttpUtils.post().url(url)
                    .addFile("uploadFile", fileDataName, file)
                    .params(params).tag(context).build()
                    .execute(new StringCallback() {

                        @Override
                        public void onResponse(String response, int id) {
                            request.success(response);
                            LogUtils.e("jsonStr", response);
                        }

                        @Override
                        public void onError(Call call, Exception e, int id) {
                            request.error(call.toString() + "失败" + e.toString());
                        }

                    });

        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
        }
    }

    /**
     * 提交一个File到服务器端。
     *
     * @param context
     * @param url
     * @param file
     * @param request
     */
    public static void requestPostFile(Context context, String url, File file,
                                       final Request request) {
//        DialogUtil.showProgressDialog(context, "正在请求网络，请稍后...");// 弹出Dialog提示，优化用户体验。

        if (NetworkUtils.isConnected(context)) {

            OkHttpUtils.postFile().url(url).file(file).tag(context).build()
                    .execute(new StringCallback() {

                        @Override
                        public void onResponse(String response, int id) {
                            request.success(response);
                            DialogUtil.dismissProgressDialog();// 隐藏进度条Dialog
                        }

                        @Override
                        public void onError(Call call, Exception e, int id) {
                            request.error("失败");
                            DialogUtil.dismissProgressDialog();// 隐藏进度条Dialog
                        }

                    });

        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
//            DialogUtil.dismissProgressDialog();// 隐藏进度条Dialog
        }
    }

    /**
     * 下载文件
     *
     * @param context
     * @param url
     * @param text
     * @param fileName
     * @param request
     */
    public static void requestDownloadFile(final Context context, String url,
                                           String text, String fileName, final Request request) {
//        Util.showProgressDialog(context, "正在请求网络，请稍后...");// 弹出Dialog提示，优化用户体验。
//        final ProgressDialog dialog = new ProgressDialog(context);
//        dialog.setTitle("正在下载");
//        dialog.setMessage(text);
//        dialog.setCancelable(false);
//        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//        dialog.show();
        //  DialogUtil.showProgressDialog(context, "正在下载，请稍后...");// 弹出Dialog提示，优化用户体验。
        if (NetworkUtils.isConnected(context)) {
            OkHttpUtils
                    .get()
                    .url(url)
                    .tag(context)
                    .build()
                    .execute(
                            new FileCallBack(Environment
                                    .getExternalStorageDirectory()
                                    .getAbsolutePath(), fileName) {

                                @Override
                                public void onResponse(File response, int arg1) {
                                    request.successFile(response);
                                    //DialogUtil.dismissProgressDialog();// 隐藏进度条Dialog


                                }

                                @Override
                                public void onError(Call arg0, Exception arg1,
                                                    int arg2) {

                                }

                                // 下载进度监听
                                @Override
                                public void inProgress(float progress, long total, int id) {
                                    super.inProgress(progress, total, id);
//                                    dialog.setProgress((int) (100 * progress));
//                                    if ((int) (100 * progress)==100){
//                                        dialog.dismiss();
//                                    }


                                }
                            });
        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
            return;
        }
    }


    /**
     * 显示图片
     *
     * @param context
     * @param url
     * @param bitmapCallback
     */
    public static void requestBitmap(Context context, String url,
                                     BitmapCallback bitmapCallback) {
//        DialogUtil.showProgressDialog(context, "正在请求网络，请稍后...");// 弹出Dialog提示，优化用户体验。

        if (NetworkUtils.isConnected(context)) {
            OkHttpUtils.get().url(url).tag(context).build().execute(bitmapCallback);
//            DialogUtil.dismissProgressDialog();// 隐藏进度条Dialog
        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
//            DialogUtil.dismissProgressDialog();// 隐藏进度条Dialog
        }
    }


    /**
     * 取消单个请求
     *
     * @param url
     */
    public static void CallCancel(String url) {
        if (url != null) {
            RequestCall call = OkHttpUtils.get().url(url).build();
            call.cancel();
        }
    }


    /**
     * 使用add添加参数,仅用于验收提交
     * @param context
     * @param url
     * @param qrbparams
     * @param request
     */
    public static void requestPostYanShou(Context context, String url,
                                   Map<String, String> qrbparams,
                                    String[] recordlist_ima,
                                    String[] advice_ima,
                                    final Request request) {

        if (NetworkUtils.isConnected(context)) {

            RequestCall call = OkHttpUtils.post().url(url)

                    .addParams("idfield", "yanshou_id")
                    .addParams("yanshou_result", qrbparams.get("yanshou_result"))
                    .addParams("yanshou_result_n", qrbparams.get("yanshou_result_n"))
                    .addParams("yanshou_time", qrbparams.get("yanshou_time"))
                    .addParams("yanshou_remark", qrbparams.get("yanshou_remark"))
                    .addParams("yanshou_opt_n", qrbparams.get("yanshou_opt_n"))
                    .addParams("yanshou_opt", qrbparams.get("yanshou_opt"))
                    .addParams("accept_date", qrbparams.get("accept_date"))
                    .addParams("buchongfu", qrbparams.get("buchongfu"))
                    .addParams("adjunct_id", recordlist_ima[0])
                    //.addParams("adjunct_id", advice_ima[0])
                    .addParams("sys_file_name", recordlist_ima[1])
                    //.addParams("sys_file_name", advice_ima[1])
                    .addParams("adjunct_type", recordlist_ima[2])
                    //.addParams("adjunct_type", advice_ima[2])
                    .addParams("file_type", recordlist_ima[3])
                    //.addParams("file_type", advice_ima[3])
                    .addParams("file_size", recordlist_ima[4])
                    //.addParams("file_size", advice_ima[4])
                    .addParams("file_des", recordlist_ima[5])
                   // .addParams("file_des", advice_ima[5])
                    .addParams("user_file_name", recordlist_ima[6])
                   // .addParams("user_file_name", advice_ima[6])
                    .tag(context).build();
            if (call == null) {
                Toast.makeText(context, "call为空", Toast.LENGTH_LONG).show();
            }
            call.execute(new StringCallback() {

                @Override
                public void onResponse(String response, int id) {
                    request.success(response);
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    request.error(call.toString() + "失败" + e.toString());
                }
            });

        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
            LoadingDialog.cancelLoadingDialog();
        }
    }



    public static void requestPostYanShou1(Context context, String url,
                                   Map<String, String> qrbparams,
                                    String[] recordlist_ima,
                                    final Request request) {

        if (NetworkUtils.isConnected(context)) {

            RequestCall call = OkHttpUtils.post().url(url)

                    .addParams("idfield", "yanshou_id")
                    .addParams("yanshou_result", qrbparams.get("yanshou_result"))
                    .addParams("yanshou_result_n", qrbparams.get("yanshou_result_n"))
                    .addParams("yanshou_time", qrbparams.get("yanshou_time"))
                    .addParams("yanshou_remark", qrbparams.get("yanshou_remark"))
                    .addParams("yanshou_opt_n", qrbparams.get("yanshou_opt_n"))
                    .addParams("yanshou_opt", qrbparams.get("yanshou_opt"))
                    .addParams("accept_date", qrbparams.get("accept_date"))
                    .addParams("buchongfu", qrbparams.get("buchongfu"))
                    .addParams("adjunct_id", recordlist_ima[0])
                    //.addParams("adjunct_id", advice_ima[0])
                    .addParams("sys_file_name", recordlist_ima[1])
                    //.addParams("sys_file_name", advice_ima[1])
                    .addParams("adjunct_type", recordlist_ima[2])
                    //.addParams("adjunct_type", advice_ima[2])
                    .addParams("file_type", recordlist_ima[3])
                    //.addParams("file_type", advice_ima[3])
                    .addParams("file_size", recordlist_ima[4])
                    //.addParams("file_size", advice_ima[4])
                    .addParams("file_des", recordlist_ima[5])
                   // .addParams("file_des", advice_ima[5])
                    .addParams("user_file_name", recordlist_ima[6])
                   // .addParams("user_file_name", advice_ima[6])
                    .tag(context).build();
            if (call == null) {
                Toast.makeText(context, "call为空", Toast.LENGTH_LONG).show();
            }
            call.execute(new StringCallback() {

                @Override
                public void onResponse(String response, int id) {
                    request.success(response);
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    request.error(call.toString() + "失败" + e.toString());
                }
            });

        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
            LoadingDialog.cancelLoadingDialog();
        }
    }

    /**
     * 仅用于检查
     * @param context
     * @param url
     * @param qrbparams
     * @param recordlist_ima
     * @param advice_ima
     * @param request
     */
    public static void requestPostJianCha(Context context, String url,
                                   Map<String, String> qrbparams,
                                    String[] recordlist_ima,
                                    String[] advice_ima,
                                    final Request request) {

        if (NetworkUtils.isConnected(context)) {

            RequestCall call = OkHttpUtils.post().url(url)
                    .addParams("idfield", "jiancha_id")
                    .addParams("jiancha_result",  qrbparams.get("jiancha_result"))
                    .addParams("jiancha_result_n", qrbparams.get("jiancha_result_n"))
                    .addParams("jiancha_time", qrbparams.get("jiancha_time"))
                    .addParams("jiancha_remark", qrbparams.get("jiancha_remark"))
                    .addParams("jiancha_opt_n", qrbparams.get("jiancha_opt_n"))
                    .addParams("jiancha_opt", qrbparams.get("jiancha_opt"))
                    .addParams("buchongfu",  qrbparams.get("buchongfu"))
                    .addParams("adjunct_id", recordlist_ima[0])
                    .addParams("adjunct_id", advice_ima[0])
                    .addParams("sys_file_name", recordlist_ima[1])
                    .addParams("sys_file_name", advice_ima[1])
                    .addParams("adjunct_type", recordlist_ima[2])
                    .addParams("adjunct_type", advice_ima[2])
                    .addParams("file_type", recordlist_ima[3])
                    .addParams("file_type", advice_ima[3])
                    .addParams("file_size", recordlist_ima[4])
                    .addParams("file_size", advice_ima[4])
                    .addParams("file_des", recordlist_ima[5])
                    .addParams("file_des", advice_ima[5])
                    .addParams("user_file_name", recordlist_ima[6])
                    .addParams("user_file_name", advice_ima[6])
                    .tag(context).build();
            if (call == null) {
                Toast.makeText(context, "call为空", Toast.LENGTH_LONG).show();
            }
            call.execute(new StringCallback() {

                @Override
                public void onResponse(String response, int id) {
                    request.success(response);
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    request.error(call.toString() + "失败" + e.toString());
                }
            });

        } else {
            ToastUtils.showShortToast(context, "网络链接失败，请检查网络设置");
            LoadingDialog.cancelLoadingDialog();
        }
    }







}
